package com.nowcoder.community.config;

import com.nowcoder.community.quartz.AlphaJob;
import com.nowcoder.community.quartz.PostScoreRefreshJob;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

/**
 * 任务调度
 * 调度流程：配置 -> 数据库 -> 调用
 * job是任务；JobDetail对job进行配置；Trigger设置job的调度:什么时候运行,以什么频率运行
 * */
@Configuration
public class QuartzConfig {
    // FactoryBean可简化Bean的实例化过程:
    // 1.通过FactoryBean封装Bean的实例化过程 2.将FactoryBean装配到Spring容器里
    // 3.将FactoryBean 注入给其他的Bean     4.该Bean得到的是 FactoryBean所管理的对象实例

    // JobDetail配置Job
    //@Bean
    public JobDetailFactoryBean alphaJobDetail() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(AlphaJob.class); //加入任务
        factoryBean.setName("alphaJob"); //任务的的名字
        factoryBean.setGroup("alphaJobGroup"); //组，多个任务可以一组
        factoryBean.setDurability(true); //任务长久保存
        factoryBean.setRequestsRecovery(true); //任务恢复
        return factoryBean;
    }

    // Trigger设置job的调度(SimpleTriggerFactoryBean, CronTriggerFactoryBean(复杂调度))
    //@Bean
    public SimpleTriggerFactoryBean alphaTrigger(JobDetail alphaJobDetail) {
        SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
        factoryBean.setJobDetail(alphaJobDetail);
        factoryBean.setName("alphaTrigger");
        factoryBean.setGroup("alphaTriggerGroup");
        factoryBean.setRepeatInterval(3000); //每3秒执行一遍
        factoryBean.setJobDataMap(new JobDataMap()); //指定存储任务的数据结构
        return factoryBean;
    }

    //JobDetail配置Job (刷新帖子分数任务)
    @Bean
    public JobDetailFactoryBean postScoreRefreshJobDetail() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(PostScoreRefreshJob.class);
        factoryBean.setName("postScoreRefreshJob");
        factoryBean.setGroup("communityJobGroup");
        factoryBean.setDurability(true);
        factoryBean.setRequestsRecovery(true);
        return factoryBean;
    }
    // Trigger设置job的调度(SimpleTriggerFactoryBean, CronTriggerFactoryBean)
    @Bean
    public SimpleTriggerFactoryBean postScoreRefreshTrigger(JobDetail postScoreRefreshJobDetail) {
        SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
        factoryBean.setJobDetail(postScoreRefreshJobDetail);
        factoryBean.setName("postScoreRefreshTrigger");
        factoryBean.setGroup("communityTriggerGroup");
        factoryBean.setRepeatInterval(1000 * 60 * 5); //时间间隔：5分钟刷新一次
        factoryBean.setJobDataMap(new JobDataMap());
        return factoryBean;
    }

}
